package com.cy.pj.sys.service.impl;

import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.sys.dao.SysMenuDao;
import com.cy.pj.sys.dao.SysRoleMenuDao;
import com.cy.pj.sys.pojo.Node;
import com.cy.pj.sys.pojo.SysMenu;
import com.cy.pj.sys.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import java.util.List;
import java.util.Map;
@Service
public class SysMenuServiceImpl implements SysMenuService {
    @Autowired
    private SysMenuDao sysMenuDao;
    @Autowired
    private SysRoleMenuDao sysRoleMenuDao;

    @Override
    public List<Map<String, Object>> findObjects() {
        return sysMenuDao.findObjects();
    }

    @Override
    public int deleteObject(Integer id) {
        //检查是否有子菜单
        if (id==null||id<1)
            throw new IllegalArgumentException("id值无效");
        int childCount = sysMenuDao.getChild(id);
        if(childCount>0)
            throw new ServiceException("请先删除子菜单");
        sysRoleMenuDao.deleteObjectsByMenuId(id);
        int row = sysMenuDao.deleteObjects(id);
        if (row==0)
            throw new ServiceException("记录可能不存在");
        return row;

    }

    @Override
    public List<Node> findZtreeMenuNodes() {
        return sysMenuDao.findZtreeMenuNodes();
    }

    @Override
    public int saveObject(SysMenu sysMenu) {
        if (sysMenu==null)
            throw new IllegalArgumentException("对象不能为空");
        if (StringUtils.isEmpty(sysMenu.getName())) {
            throw new IllegalArgumentException("菜单名不能为空");
        }
        int rows = sysMenuDao.insertObject(sysMenu);

        return rows;
    }

    @Override
    public int updateObject(SysMenu entity) {
        //1.合法验证
        if(entity==null)
            throw new ServiceException("保存对象不能为空");
        if(StringUtils.isEmpty(entity.getName()))
            throw new ServiceException("菜单名不能为空");

        //2.更新数据
        int rows=sysMenuDao.updateObject(entity);
        if(rows==0)
            throw new ServiceException("记录可能已经不存在");
        //3.返回数据
        return rows;

    }


}
